<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="hAdd"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="list">
              <el-table-column label="序号" width="120" type="index" />
              <el-table-column prop="name" label="角色名称" width="240" />
              <el-table-column prop="description" label="描述" />
              <el-table-column label="操作">
                <template #default="{row}">
                  <el-button size="small" type="success" @click="hAssign(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="hEdit(row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="hDel(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                :current-page="queryParams.page"
                :page-sizes="[2, 3, 5, 10,20]"
                :page-size="queryParams.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <el-dialog
        title="新增角色"
        :visible.sync="dialogVisible"
        :close-on-click-modal="false"
        @close="hReset"
      >
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="hClose">取消</el-button>
            <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
      <!-- 分配权限的弹层 -->
      <el-dialog
        title="分配权限(一级为路由页面查看权限-二级为按钮操作权限)"
        :visible.sync="showDialogAssign"
      >
        <assignPermission v-if="showDialogAssign" :id="curId" @close="showDialogAssign=false" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getRoles, addRoles, updateRoles, delRoles } from '@/api/settings'
import assignPermission from './assignPermission.vue'
export default {
  components: {
    assignPermission
  },
  data() {
    return {
      showDialogAssign: false,
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      dialogVisible: false, // 控制对话框的显示隐藏
      list: [], // 保存所有的角色列表
      queryParams: { // 获取角色列表需要的参数
        page: 1,
        pagesize: 2
      },
      total: 0,
      isEdit: false,
      curId: ''
    }
  },
  created() {
    this.loadRoles()
  },

  methods: {

    hAssign(id) {
      this.showDialogAssign = true
      this.curId = id
    },
    // 取消按钮关闭弹窗
    hClose() {
      this.dialogVisible = false
    },
    // 重置表单
    hReset() {
      this.$refs.roleForm.resetFields()
      this.roleForm = {
        name: '',
        description: ''
      }
    },
    // 实现删除
    async hDel(id) {
      this.$confirm('确定删除该角色吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delRoles(id)
        if (this.list.length === 1) {
          this.queryParams.page--
          if (this.queryParams.page === 0) {
            this.queryParams.page = 1
          }
        }
        // 重新渲染
        this.loadRoles()
      })
    },

    // 实现新增
    async doAdd() {
      try {
        await addRoles(this.roleForm)
        this.total++
        // 实现新增完成跳转到新增的页面
        const maxPage = Math.ceil(this.total / this.queryParams.pagesize)
        this.queryParams.page = maxPage
        // 重新渲染
        this.loadRoles()
        // 关闭弹窗
        this.dialogVisible = false
      } catch (error) {
        console.log(error)
      }
    },

    // 实现编辑
    async doEdit() {
      try {
        await updateRoles(this.roleForm)
        // 重新渲染
        this.loadRoles()
        // 关闭弹窗
        this.dialogVisible = false
      } catch (error) {
        console.log(error)
      }
    },
    // 编辑操作
    hEdit(data) {
      //
      this.isEdit = true
      // 将表格中获取到的数据填充到表格
      // 因为this.roleForm进行了表单的双向绑定,this.roleForm也会发生改变
      // 而this.roleForm和传进来的data(表单的数据对象),所有导致,表单的数据改变,变革中的数据跟着改变
      // 解决的办法 使用浅拷贝
      this.roleForm = { ...data }
      // 打开弹窗
      this.dialogVisible = true
    },
    // 新增操作
    hAdd() {
      this.dialogVisible = true
      //
      this.isEdit = false
    },
    hSubmit() {
      // 兜底校验
      this.$refs.roleForm.validate(valid => {
        // 校验失败
        if (!valid) return
        // 校验通过
        // 判断是编辑还是新增
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    // 获取角色列表数据
    async loadRoles() {
      try {
        const { data: res } = await getRoles(this.queryParams)
        // console.log(res)
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    },
    // 实现控制每页条数变化切换数据变化
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.queryParams.page = 1
      this.queryParams.pagesize = val
      this.loadRoles()
    },
    // 实现翻页功能
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.queryParams.page = val
      this.loadRoles()
    }
  }
}

</script>
